#!/bin/bash

# get current date and time
CURRENT_DATE=$(date "+%Y-%m-%d")
CURRENT_TIME=$(date "+%Y-%m-%d-%H-%M")

# deploy related variables
CODE_DIR="/deploy/code/demo"
CONFIG_DIR="/deploy/config"
TEMP_DIR="/deploy/temp"
TAR_DIR="/deploy/tar"

usage() {
    echo $"Usage: $0 [deploy | rollback-list | rollback-pro version]"
}

git_pull_pro() {
    echo "Begin git pull"
    cd ${CODE_DIR} && git pull
    API_VERSION_LONG=$(git show |grep commit |cut -d' ' -f2)
    API_VERSION=$(echo ${API_VERSION_LONG:0:6})
    cp -r "${CODE_DIR}" "${TEMP_DIR}"
}

config_pro() {
    echo "add pro config"
    /bin/cp "${CONFIG_DIR}"/* "${TEMP_DIR}"/demo/
    TAR_VERSION=${API_VERSION}_${CURRENT_TIME}
    cd ${TEMP_DIR} && mv demo pro_demo_${TAR_VERSION}
}

tar_pro() {
    echo "begin tar pro"
    cd ${TEMP_DIR} && tar -czf pro_demo_${TAR_VERSION}.tar.gz pro_demo_${TAR_VERSION} 
    echo "end tar pro_demo_${TAR_VERSION}.tar.gz"
}

scp_pro() {
    echo "begin scp"
    /bin/cp ${TEMP_DIR}/pro_demo_${TAR_VERSION}.tar.gz /tmp
}

deploy_pro() {
    echo "begin deploy"
    cd /tmp && tar -xf pro_demo_${TAR_VERSION}.tar.gz
    rm -rf /var/www/html/demo
    ln -s /tmp/pro_demo_${TAR_VERSION} /var/www/html/demo
}

test_pro() {
    echo "begin test"
    echo "curl test ok"
}

rollback_list() {
    ls -l /tmp/*.tar.gz
}

rollback_pro() {
    rm -f /var/www/html/demo
    ln -s /tmp/$1 /var/www/html/demo
}

main() {
    case $1 in
        deploy)
            git_pull_pro
            config_pro
            tar_pro
            scp_pro
            deploy_pro
            test_pro
            ;;
        rollback-list)
            rollback_list
            ;;
        rollback-pro)
            rollback_pro $2
            ;;
        *)
            usage
            ;;
        esac
}

main $1 $2
